package com.batch.config;

import com.batch.pojo.Scores;
import jakarta.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableBatchProcessing
public class CsvBatchJobConfig {
/*	@Resource
	JobBuilder jobBuilderFactory;
	@Resource
	StepBuilder stepBuilderFactory;*/
	@Resource
	JobRepository jobRepository;
	@Resource
	PlatformTransactionManager transactionManager;
	@Resource
	DataSource dataSource;
	@Bean
	@StepScope
	FlatFileItemReader<Scores> itemReader(){
		FlatFileItemReader<Scores> reader=new FlatFileItemReader<>();
		reader.setLinesToSkip(1);
		reader.setResource(new ClassPathResource("data.csv"));
		reader.setLineMapper(new DefaultLineMapper<>(){{
			setLineTokenizer(new DelimitedLineTokenizer(){{
				setNames("id","coursename","score");
				setDelimiter(" ");
			}});
			setFieldSetMapper(new BeanWrapperFieldSetMapper<>(){{
				setTargetType(Scores.class);
			}});
		}});
		return reader;
	}
	@Bean
	JdbcBatchItemWriter jdbcBatchItemWriter(){
		JdbcBatchItemWriter<Object> writer = new JdbcBatchItemWriter<>();
		writer.setDataSource(dataSource);
		writer.setSql("insert into scores(id,coursename,score) values(:id,:coursename,:score)");
		writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>());
		return writer;
	}
	@Bean
	Step csvStep(){
		return new StepBuilder("csvStep",jobRepository).<Scores,Scores>chunk(2,transactionManager).reader(itemReader()).writer(jdbcBatchItemWriter()).build();
				/*stepBuilderFactory.get("csvStep").<Scores,Scores>chunk(2).reader(itemReader()).writer(jdbcBatchItemWriter()).build();*/
	}
	@Bean
	Job csvJob(){
		return new JobBuilder("csvJob",jobRepository)
				.start(csvStep())
				.build();
//				jobBuilderFactory.get("csvJob").start(csvStep()).build();
	}
}
